package com.sxl.ocr.ocronnx.controller;

import com.sxl.ocr.ocronnx.model.R;
import com.sxl.ocr.ocronnx.service.OCRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.FormFieldPart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.File;

/**
 * description:
 * author: shenxiaolong
 * date: 2021/1/27  15:14
 */
@RequestMapping("/ocr")
@RestController
public class OCRController {

    @Autowired
    private OCRService ocrService;

    @Value("${ocr.tmpDir}")
    private String tmpDir;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<R<OCRService.OcrResultVo>> getOcrResult(@RequestPart("file") FilePart filePart,
                                                        @RequestPart("imgResize") FormFieldPart imgResize) {

        String filename = filePart.filename();
        String value = imgResize.value();
        File tmp = new File(tmpDir + filename);

        return Mono
                .just(filePart)
                .flatMap(file -> file.transferTo(tmp))
                .then(Mono.just(value))
                .map(Integer::parseInt)
                .flatMap(v -> Mono.just(R.success(ocrService.getOnnxOcrResult(tmp, v))))
                .onErrorResume(e -> Mono.just(R.fail(1001, "Error: " + e.getMessage())));
    }

}
